<?php

namespace app\common\libs;

use JsonException;
use yiqiniu\extend\facade\Redis;

/**
 * 根据经纬度获取地区
 */
class Area
{


    //经纬度
    protected $lng = '';
    protected $lat = '';

    //省市县区域
    protected  $namearr = [1 => 'province', 2 => 'city', 3 => 'district',4 =>'formatted_address'];

    //百度apikey
    protected $place_url = '';
    protected $api_key = 'j6d2zTfenprZIo4mWigRUfUr4oxnXCf1';


    private static $_instance = null;

    public static function getInstance($lat, $lng): ?Area
    {
        if (self::$_instance === null) {
            self::$_instance = new static();
        }
        self::$_instance->lng = $lng;
        self::$_instance->lat = $lat;
        self::$_instance->place_url = sprintf(config('Area.app_host'),$lng,$lat,self::$_instance->api_key);
        return self::$_instance;
    }

    /**
     * 根据经纬度获取当前地区信息
     * @param string $lng 经度
     * @param string $lat 纬度
     * @param int $level 区域
     * @throws JsonException
     */
    public static function getAreaFromLngLat(string $lng, string $lat, int $level)
    {
        $location = self::$_instance->namearr[$level];
        $place_arr = Redis::get(md5($lng . $lat));

        if (empty($place_arr)) {
            $place_arr = json_decode(file_get_contents(self::$_instance->place_url), true, 512, JSON_THROW_ON_ERROR);
            Redis::set(md5($lng . $lat), $place_arr , 60);
        }

        if (empty($place_arr) || ($place_arr['status'] !== 'OK')){
            return '';
        }

        if ($level > 3) {
            return $place_arr['result'][$location] ?: '';
        }
        return $place_arr['result']['addressComponent'][$location] ?: '';
    }

    /**
     * 根据经纬度获取省份
     * @throws JsonException
     */
    public function getProvinceFromLngLat()
    {
        return self::getAreaFromLngLat(self::$_instance->lng, self::$_instance->lat, 1);
    }

    /**
     * 根据经纬度获取城市
     * @throws JsonException
     */
    public function getCityFromLngLat(): string
    {
        return self::getAreaFromLngLat(self::$_instance->lng, self::$_instance->lat, 2);
    }

    /**
     * 根据经纬度获取地区
     * @throws JsonException
     */
    public function getDistrictFromLngLat()
    {
        return self::getAreaFromLngLat(self::$_instance->lng, self::$_instance->lat, 3);
    }

    /**
     * 根据经纬度获取所有地址
     * @throws JsonException
     */
    public function getLocationLat()
    {
        return self::getAreaFromLngLat(self::$_instance->lng, self::$_instance->lat, 4);
    }
}
